<template>
  <view>
    <!-- 加入placeholder就可以把顶部撑下来 -->
    <uv-navbar title="修改个人信息" border left-icon="" placeholder></uv-navbar>
  </view>

  <!-- 页面主要部分 -->
  <view class="body-container">
    <!-- <uv-input type="text" placeholder="测试用"></uv-input> -->
    <uv-form :model="user" :rules="rules" ref='form' label-width="130rpx">
      <uv-form-item label="用户名" prop="username" border-bottom>
        <uv-input v-model="user.username" type="text" placeholder="用户名只可修改一次" :disabled=!!hasUsername></uv-input>
      </uv-form-item>
      <uv-form-item label="密码" prop="password" border-bottom>
        <uv-input v-model="user.password" type="password" placeholder="请输入密码" password></uv-input>
      </uv-form-item>
      <uv-form-item label="确认密码" prop="rePassword" border-bottom>
        <uv-input v-model="user.rePassword" type="password" placeholder="请再次输入密码"></uv-input>
      </uv-form-item>
    </uv-form>
  </view>

  <view>
    <!-- 底部 -->
    <bottomTab type='submit'></bottomTab>
  </view>

</template>

<script setup>
  import {
    computed,
    ref
  } from 'vue';
  import nx from '@/nx';
  import {onLoad, onUnload} from '@dcloudio/uni-app'
  import getStorageItem from '@/utils/getStorageItem';
  defineOptions({
    name: "userInfoEdit",
  })
  const form = ref(null)
  const hasUsername = getStorageItem('user')?.userInfo.username
  const user = ref({
    username: hasUsername,
    password: '',
    rePassword: '',
  })
  const rules = ref({
    username: [{
        type: 'string',
        min: 5,
        max: 10,
        required: true,
        message: '用户名需为5-10位',
        trigger: ['blur']
      }, {
        // 校验用户名是否重复
        asyncValidator: async (rule, value, callback) => {
          // console.log(callback);
          let resp = await nx.$api.user.testUsername({
            username: value
          })
          if (resp.code === 200 ){
            // 成功，用户名不重复
            callback()
          } else {
            // 失败用户名重复
            callback(new Error(resp.msg))
          }
          // .then(resp =>{
          //   console.log(resp);
          //   callback()
          // }).catch(error =>{
          //   console.log('检验失败');
          //   callback(new Error(error.msg))
          // })
          // if (resp.code === 200) {
            
          //   callback()
          // } else {
          //   console.log('检验失败');
          //   callback(new Error('用户名已存在'))
          // }
        },
        trigger: ['blur']
        // .then(res => {
        //   // 如果验证不通过，需要在callback()抛出new Error('错误提示信息')
        //   if (res.error) {
        //     callback(new Error('用户名已存在'));
        //   } else {
        //     // 如果校验通过，也要执行callback()回调
        //     callback();
        //   }
        // })
      // 如果是异步校验，无需写message属性，错误的信息通过Error抛出即可
      // message: 'xxx'
    }],
  password: {
    type: 'string',
    pattern: /^(?=.*\d)(?=.*[A-z])[\da-zA-Z]{6,16}$/,
    required: true,
    message: '密码需为6-16位，由数字、字母组成',
    trigger: ['blur']
  },
  rePassword: [{
    type: 'string',
    pattern: /^(?=.*\d)(?=.*[A-z])[\da-zA-Z]{6,16}$/,
    required: true,
    message: '密码需为6-16位，由数字、字母组成',
    trigger: ['blur']
  }, {
    validator: (rule, value, callback) => {
      // 两次输入是否一致
      return value === user.value.password
    },
    trigger: ['blur'],
    message: '两次输入密码不一致，请检查'
  }]
  })
  const submit = () => {
    // console.log();
    // console.log(form.value.validate);
    form.value.validate().then(async res => {
      let resp = await nx.$api.user.updateInfo(user.value)
      if (resp.code === 200) {
        // console.log("提交成功", resp)
        // 再次获取下客户信息
        await nx.$store('user').getInfo()
        uni.showToast({
          title: '修改成功',
          icon: 'success'
        })
        // 返回上一页
        uni.switchTab({
          url:'/pages/me/index',
        })
      }
      // console.log("提交成功", res)
    }).catch(error => {
      uni.showToast({
        title: '提交失败',
        icon: 'error'
      })
    })
  }
  // const hasUsername = computed(()=>{

  // })

  onLoad(() => {
    uni.$on('bottomTabSubmit', () => {
      console.log(user.value);
      submit()
    })
  })
  
  // onUnload(() => {
  //   uni.$off('bottomTabSubmit')
  // })

  
  




  // const topDiv = ref({'margin-top': ''})

  // let statusBarHeight = uni.getSystemInfoSync().statusBarHeight
  // console.log("系统信息", info);
</script>

<style lang="scss" scoped>
  // .body-container {
  //   margin: 30rpx;
  // }
</style>